package cn.jhc.servlet;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.sql.DataSource;

import cn.jhc.bean.User;
import cn.jhc.db.UserDao;
import cn.jhc.utils.Constants;

/**
 * Servlet implementation class CheckUniqueServlet
 */
@WebServlet("/checkUnique.do")
public class CheckUniqueServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public CheckUniqueServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		DataSource dataSource = (DataSource)request.getServletContext().getAttribute(Constants.H2_DATASOURCE);
		String isbn = request.getParameter("isbn");
		System.out.println(isbn);
		response.setContentType("appliction/json;charset=utf8");		
		PrintWriter out = response.getWriter();
		UserDao userDao = new UserDao(dataSource);
		User user = new User();
		user.setUsername(isbn);
		if(userDao.selectbyname(user)==true){
			out.println("{\"unique\":\"true\"}");
		}
		else {
			out.println("{\"unique\":\"false\"}");
		}
	}
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		DataSource dataSource = (DataSource)request.getServletContext().getAttribute(Constants.H2_DATASOURCE);
		String isbn = request.getParameter("isbn");
		System.out.println(isbn);
		response.setContentType("appliction/json;charset=utf8");		
		PrintWriter out = response.getWriter();
		UserDao userDao = new UserDao(dataSource);
		User user = new User();
		user.setUsername(isbn);
		if(userDao.selectbyname(user)==true){
			out.println("{\"unique\":\"true\"}");
		}
		else {
			out.println("{\"unique\":\"false\"}");
		}
	}

}
